package com.yand.oratransmysql.thread;

import com.yand.oratransmysql.constant.Constant;
import com.yand.oratransmysql.entity.DataBaseConvert;
import com.yand.oratransmysql.entity.OracleTableColumnInfoBean;
import com.yand.oratransmysql.service.MysqlService;
import com.yand.oratransmysql.service.OracleTableService;
import com.yand.oratransmysql.utils.DateUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CountDownLatch;


public class DbConvertFileThread implements Runnable{
    private static final Logger logger = LoggerFactory.getLogger("dbConvertFileThread");

    private DataBaseConvert dataBaseConvert;

    public DbConvertFileThread(DataBaseConvert dataBaseConvert){
        this.dataBaseConvert = dataBaseConvert;
    }


    /**
     * 进行处理
     */
    @Override
    public void run() {
        String tableName = dataBaseConvert.getTableName();

        CountDownLatch countDownLatch = dataBaseConvert.getCountDownLatch();

        OracleTableService oracleTableService = dataBaseConvert.getOracleTableService();

        try {

            //创建文件名
            String fileName = dataBaseConvert.getTableName()+".sql";
            File file = new File(Constant.filePath+fileName);
            file.createNewFile();
            //查询该表的列名与列类型
            List<OracleTableColumnInfoBean> columnInfoBeanList = oracleTableService.queryTableColumnInfoByName(tableName);
            Map<String, Object> param = new HashMap<>();
            param.put("tableName",tableName);
            BigDecimal dataCount = oracleTableService.queryDataCount(param);
            logger.info("表:"+tableName+"中有记录"+dataCount.intValue()+"条.");
            int size = (int)Math.ceil((dataCount.divide(new BigDecimal(Constant.pageSize))).doubleValue());
            List<String> sqlLineList = new ArrayList<>();
            for(int i = 0 ; i < size; i ++){
                param.put("begin",Constant.pageSize*i);
                param.put("end", Constant.pageSize*(i+1));
                List<Map<String, Object>> dataList = oracleTableService.queryDataList(param);
                String sqlLine = "";
                String lineSqlStart = lineSqlStart(tableName, columnInfoBeanList);
                for(Map<String, Object> data : dataList){
                    sqlLine = lineSqlStart;
                    String lineSqlEnd = columnTextSql(data, columnInfoBeanList);
                    sqlLine += lineSqlEnd;
                    //将每一行的sql写入到文件中
                    sqlLineList.add(sqlLine);
                }
            }
            //写入文件中
            FileUtils.writeLines(file, sqlLineList);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            countDownLatch.countDown();
        }

    }

    //拼接每一行sql的头
    private String lineSqlStart(String tableName, List<OracleTableColumnInfoBean> columnInfoBeanList){
        StringBuffer buffer = new StringBuffer();
        buffer.append("INSERT INTO "+ tableName + " (");
        int index = 0;
        for(OracleTableColumnInfoBean columnInfoBean : columnInfoBeanList){
            index ++;
            buffer.append(columnInfoBean.getColumnName());

            if(index < columnInfoBeanList.size()){
                buffer.append(",");
            }

        }
        buffer.append(")");
        return buffer.toString();
    }



    /**
     * 拼接每一列的类型以及值
     * @param data
     * @param columnInfoBeanList
     * @return
     */
    private String columnTextSql(Map<String, Object> data, List<OracleTableColumnInfoBean> columnInfoBeanList){

        StringBuffer lineSqlEnd = new StringBuffer();
        lineSqlEnd.append("values(");
        int index = 0;
        for(OracleTableColumnInfoBean columnInfoBean : columnInfoBeanList){
            index ++;
            String columnName = columnInfoBean.getColumnName();
            String columnType = columnInfoBean.getColumnType();
            Object columnText = data.get(columnName);
            if(columnText == null){
                lineSqlEnd.append("null");
            }else {
                switch (columnType) {
                    case "VARCHAR2":
                        lineSqlEnd.append("'" + columnText.toString() + "'");
                        break;
                    case "NUMBER":
                        lineSqlEnd.append(((BigDecimal) columnText).intValue());
                        break;
                    case "DATE":
                        lineSqlEnd.append("STR_TO_DATE('" + DateUtils.parseDate((Date) columnText) + "','%Y-%m-%d %H:%i:%s')");
                        break;

                }
            }

            if(index < columnInfoBeanList.size()){
                lineSqlEnd.append(",");
            }

        }
        lineSqlEnd.append(");");

        return lineSqlEnd.toString();



    }


}
